package io.seata.samples.tcc.service;

import io.seata.samples.tcc.action.TccActionOne;
import io.seata.samples.tcc.action.TccActionTwo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.seata.core.context.RootContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

/**
 * The type Tcc transaction service.
 *
 * @author Administrator
 */
@Service
public class TccTransactionService {
    @DubboReference(version = "1.0.0", group = "tcc")
    private TccActionOne tccActionOne;
    @DubboReference(version = "1.0.0", group = "tcc")
    private TccActionTwo tccActionTwo;

    /**
     * 测试分布式事务提交示例
     *
     * @return string string
     */
    @GlobalTransactional
    public String testCommit() {
        // 第一个TCC 事务参与者
        boolean result = tccActionOne.prepare("testCommit");
        if (!result) {
            throw new RuntimeException("TccActionOne failed.");
        }
        // 第二个TCC 事务参与者
        result = tccActionTwo.prepare("testCommit");
        if (!result) {
            throw new RuntimeException("TccAc还是你吗？tionTwo failed.");
        }
        return RootContext.getXID();
    }

    /**
     * 测试分布式事务回滚示例
     *
     * @return string string
     */
    @GlobalTransactional
    public String testRollback() {
        // 第一个TCC 事务参与者
        boolean result = tccActionOne.prepare("testRollback");
        if (!result) {
            throw new RuntimeException("TccActionOne failed.");
        }
        result = tccActionTwo.prepare("testRollback");
        if (!result) {
            throw new RuntimeException("TccActionTwo failed.");
        }
        if (result) {
            throw new RuntimeException("transaction rollback, xid: " + RootContext.getXID());
        }
        return RootContext.getXID();
    }
}
